//app.js
var util = require("/utils/util.js")
var md5 = require("/utils/md5.js");
var CryptoJS = require("/utils/CryptoJS.js")
App({
  onLaunch: function (options) {
    var _this = this
    wx.removeStorageSync('sessionid');
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: this.globalData.baseUrl + 'auth/jwt/session-key?code=' + res.code + '&museumCode=' + _this.globalData.museumCode,
          header: {
            'content-type': 'application/json',
          },
          success(res) {
            console.log('onLaunch', res.data)
            console.log(res.header)
            if (res && res.header && res.header['Set-Cookie']) {
              console.log('保存cookie', res)
              wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
            }
            if (res.data.rel) {
              wx.setStorageSync('openId', res.data.data)
            }
          }
        })
      }
    })
    //登录校验
    wx.checkSession({
      success() {
        console.log('未过期')
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        // 登录
        wx.removeStorageSync('sessionid');
        wx.login({
          success: res => {
            console.log(res.code)
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            wx.request({
              url: _this.globalData.baseUrl + 'auth/jwt/session-key?code=' + res.code + '&museumCode=' + _this.globalData.museumCode,
              header: {
                'content-type': 'application/json'
              },
              success(res) {
                console.log('过期了', res.data)
                if (res && res.header && res.header['Set-Cookie']) {
                  console.log('保存cookie', res)
                  wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
                }
                if (res.data.rel) {
                  wx.removeStorageSync('token')
                  wx.setStorageSync('openId', res.data.data)
                }
              }
            })
          }
        })
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              console.log(res.userInfo)
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        console.log('onCheckForUpdate====', res)
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          console.log('res.hasUpdate====')
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                console.log('success====', res)
                // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    }

    //公众号
    if (options.query.fid != undefined && options.query.fid != "" && options.query.fidEnc != undefined && options.query.fidEnc != "") {
      this.globalData.fid = options.query.fid;
      this.globalData.fidEnc = options.query.fidEnc;
      this.globalData.allowLocation = true;
      this.checkFidEnc(options.query.fidEnc);
    } else {
      this.globalData.allowLocation = false
    }
    //提前获取code，登录使用
    let cxid = wx.getStorageSync('cxid');
    if (cxid && cxid > 0) {

    } else {
      wx.login({
        success: res => {
          if (res.errMsg == 'login:ok') {
            wx.setStorageSync('code', res.code);
          }
        }
      })
    }

    this.globalData.innerAudioContext = wx.getBackgroundAudioManager();
    var that = this;
    // that.checkFidEnc(that.globalData.fidEnc);

  },

  //初始化
  init: function (options) {
    this.globalData.innerAudioContext = wx.getBackgroundAudioManager(); //播放对象
    var that = this;
    console.log("进入小程序");
    if (options.query.fid != undefined && options.query.fid != "" && options.query.fidEnc != undefined && options.query.fidEnc != "") {
      this.globalData.fid = options.query.fid;
      this.globalData.fidEnc = options.query.fidEnc;
      this.globalData.allowLocation = true;
      this.checkFidEnc(options.query.fidEnc);
    } else {
      this.globalData.allowLocation = false
    }

    let cxid = wx.getStorageSync('cxid');
    if (cxid && cxid > 0) {

    } else {
      wx.login({
        success: res => {
          console.log(res);
          if (res.errMsg == 'login:ok') {
            wx.setStorageSync('code', res.code);
          }
        }
      })
    }
  },
  url:{
    pictureBaseUrl : 'https://shaoerhuiben.chaoxing.com/',
    bookBaseUrl : 'https://bookshequ3.chaoxing.com/',
    wxgtBaseUrl : 'https://wxgt.chaoxing.com/',
    audiobookBaseUrl : 'https://audiobook.chaoxing.com/',
    scoreshequ3BaseUrl : 'https://scoreshequ3.chaoxing.com/',
    soshequ3BaseUrl: 'https://soshequ3.chaoxing.com/',
    videoshequ3BaseUrl:'https://videoshequ3.chaoxing.com/',
    manageshequ3BaseUrl:'https://manageshequ3.chaoxing.com/'
  },
  globalData: {
    // 开发环境
    // baseUrl: "http://192.168.20.50:10010/api/",
    // adminUrl: 'http://192.168.20.50:10010/api/admin/front/',
    // imgUrl: "http://192.168.20.50/file/",
    // museumCode: "jnsbwg",
    // 测试环境
    // baseUrl: "https://cloud-museum.chaoxing.com/api/",
    // adminUrl: 'https://cloud-museum.chaoxing.com/api',
    // imgUrl: "https://museum.chaoxing.com/micro-upload-test/",
    // museumCode: "jinanshibowuguan",
    // slotName:'banner',
    // 生产环境
    baseUrl: "https://museum-backend.chaoxing.com/api/",
    adminUrl: 'https://cloud-museum.chaoxing.com/api',
    imgUrl: "https://museum.chaoxing.com/micro-upload/",
    museumCode: "gyxwb",
    slotName: 'banner',
    api_token: null,
    userInfo: null,
    fid: 152288,
    fidEnc: '1d3d1e2bcee6ca7c',
    version: "2.0.0",
    cxid: 0,
    islogin: false,
    appId: 'wxfe3b51722fc1e03b',
    islogin: false,
    innerAudioContext: null,
    pro_superlib: 'Y7chE6j&jd#g*GMdjM',
    allowLocation: false,
    province: '',
    city: '',
    district: '',
    latitude: '',
    longitude: '',
    site: null,
    passEnc: false,
    shareImgSrc: [
      'https://wxgt.chaoxing.com/static/images/img0312/canvas_banner1.jpg',
      'https://wxgt.chaoxing.com/static/images/img0312/canvas_banner2.png',
      'https://wxgt.chaoxing.com/static/images/img0312/canvas_banner3.png',
      'https://wxgt.chaoxing.com/static/images/img0312/canvas_banner4.png'
    ],
    wxTypes: [{
        'name': 'book',
        'id': 1
      }, //图书
      {
        'name': 'qk',
        'id': 2
      }, //期刊
      {
        'name': 'lecture',
        'id': 3
      }, //讲座
      {
        'name': 'huiben',
        'id': 4
      }, //绘本
      {
        'name': 'audio',
        'id': 5
      }, //听书
      {
        'name': 'activity',
        'id': 6
      }, //作品征集
      {
        'name': 'creditcenter',
        'id': 7
      }, //积分商城
      {
        'name': 'score',
        'id': 8
      }, //积分服务
      {
        'name': 'poem',
        'id': 9
      }, //主题展topic
      {
        'name': 'topic',
        'id': 10
      }, //专题
      {
        'name': 'clock',
        'id': 11
      }, //学习打卡
      {
        'name': 'challenge',
        'id': 12
      }, //知识挑战
      {
        'name': 'office',
        'id': 13
      } //办公应用
    ],
    bbsid: '', //小组id
    circleId: 0,
    bbsidMsg: {},
    userImgSrc: "",
    activityHost: 'https://huibenbook.chaoxing.com/activity'
  },



  //进入小程序
  onShow: function (options) {
    this.globalData.gede = 'https://s' + this.globalData.fid + '-gede.zsjy.chaoxing.com';
    this.globalData.shaoerhuiben = 'https://s' + this.globalData.fid + '-shaoerhuiben.zsjy.chaoxing.com';
    this.globalData.pro = 'https://s' + this.globalData.fid + '-pro.zsjy.chaoxing.com';
    this.globalData.punch = 'https://s' + this.globalData.fid + '-punch.zsjy.chaoxing.com';
    this.globalData.entry = 'https://s' + this.globalData.fid + '-entry.zsjy.chaoxing.com';
    this.globalData.external = 'https://s' + this.globalData.fid + '-external.zsjy.chaoxing.com',
      this.globalData.video = 'https://s' + this.globalData.fid + '-video3.zsjy.chaoxing.com'
    this.globalData.newsInfo = 'https://' + this.globalData.fid + '-info.zsjy.chaoxing.com'
    //this.checkSession()
    //公众号
    if (options.query.fid != undefined && options.query.fid != "" && options.query.fidEnc != undefined && options.query.fidEnc != "") {
      this.globalData.fid = options.query.fid;
      this.globalData.fidEnc = options.query.fidEnc;
      this.globalData.allowLocation = true;
      this.checkFidEnc(options.query.fidEnc);
    } else {
      console.log('检查缓存中是否有单位信息')
      this.globalData.allowLocation = false;
      this.checkSession(); //检查缓存中是否有单位信息
    }
    this.getMuseumCode(this.globalData.fid)
  },

  //退出小程序
  onHide: function () {

  },

  /**
   * 校验fidEnc
   */
  checkFidEnc: function (fidEnc) {
    var that = this;
    var encarr = [{
      fidEnc: fidEnc
    }]
    var enc = that.generateEnc(encarr)
    wx.request({
      url: 'https://manageshequ3.chaoxing.com/api/checkfidenc?fidEnc=' + fidEnc+ '&enc=' + enc,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          let site = res.data.data;
          try {
            JSON.parse(site.custom)
          } catch (error) {
            site.custom = site.custom != '' ? that.decrypt(site.custom) : site.custom
            site.appid = site.appid!=''?that.decrypt(site.appid):site.appid
            site.fidEnc = site.fidEnc!=''?that.decrypt(site.fidEnc):site.fidEnc
            site.fidEncH5 = site.fidEncH5!=''?that.decrypt(site.fidEncH5):site.fidEncH5
            site.secret = site.secret!=''?that.decrypt(site.secret):site.secret
          }
          that.globalData.passEnc = true;
          that.globalData.fid = site.fid;
          that.globalData.site = site;
          // wx.setStorageSync("fid", site.fid);
          //2020-03-24 需要判断下缓存中单位与pages/index/index?fid=xxxxx这个单位是否为同一个，不同的话，切换fid,并清空登录信息
          var cxid = wx.getStorageSync('cxid');
          var fid = wx.getStorageSync('fid');
          if (cxid && cxid > 0 && fid && fid > 0) {
            if (fid != that.globalData.fid) {
              wx.setStorageSync('fid', that.globalData.fid); //切换fid
              wx.removeStorageSync('cxid'); //清空cxid
              wx.removeStorageSync('userInfo'); //清空userinfo
              console.log("清空用户信息");
              wx.setStorageSync('site', site); //更新site
              wx.removeStorageSync('openid'); //清空openid
              wx.removeStorageSync('phone'); //清空phone
              // wx.removeStorageSync('openid4');//清空openid4
              wx.removeStorageSync('session_key'); //清空sessionkey
              wx.setStorageSync('hasLogin', false); //切换登录状态
              wx.setStorageSync('permission', false); //切换登录状态
            }
          } else {
            wx.setStorageSync("fid", site.fid);
            wx.setStorageSync('site', site); //更新site
          }
        } else {
          console.log("enc校验未通过")
        }

      },
      fail: function () {
        console.log("校验服务器出错")
      }
    })
  },

  /**
   *微信直接访问小程序时判断当前单位和登录状态
   */
  checkSession: function () {
    var fid = wx.getStorageSync('fid');
    //  var fid = this.globalData.fid;
    if (fid != undefined && fid != null && fid != "") {
      this.globalData.fid = fid;
      var that = this;
      var encarr = [{
        fid: fid
      }]
      var enc = that.generateEnc(encarr)
      wx.request({
        url: 'https://manageshequ3.chaoxing.com/api/getsitebyfid?fid=' + fid + '&enc=' + enc,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.code == 200) {
            let site = res.data.data;
            try {
              JSON.parse(site.custom)
            } catch (error) {
              site.custom = site.custom != '' ? that.decrypt(site.custom) : site.custom
              site.appid = site.appid!=''?that.decrypt(site.appid):site.appid
              site.fidEnc = site.fidEnc!=''?that.decrypt(site.fidEnc):site.fidEnc
              site.fidEncH5 = site.fidEncH5!=''?that.decrypt(site.fidEncH5):site.fidEncH5
              site.secret = site.secret!=''?that.decrypt(site.secret):site.secret
            }
            that.globalData.fid = site.fid;
            that.globalData.site = site;
            if (site.data) {
              that.globalData.bbsid = site.data.communityId
              that.globalData.bbsidMsg = site.data
            }
          } else {
            console.log("fid不存在");
          }

        },
        fail: function () {
          console.log("校验服务器出错")
        }
      })
    }
  },

  //根据fid获取museumCode
  getMuseumCode(fid) {
    let that = this
    wx.request({
      url: that.globalData.baseUrl + 'admin/front/group/code',
      // url: 'http://120.92.71.241:8028/api/admin/front/group/code',
      method: 'get',
      data: {
        fid: fid
      },
      success: function (res) {
        if (res.statusCode == 200) {
          console.log("根据fid获取museumCode")
          console.log(res)
          console.log("获取museumCode成功", res);
          let data = res.data
          if (data && data.status == 200) {
            that.globalData.museumCode = data.data;
          } else {
            console.log("获取museumCode失败");
          }
        } else {
          console.log("获取museumCode失败");
        }
      },
      fail: function () {
        console.log("获取museumCode失败");
      }
    })
  },
 // aes解密
 decrypt: function (val) {
  var value = CryptoJS.DES.decrypt(val, CryptoJS.enc.Utf8.parse('Def@uiT8KeYw4Ev5'), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString(CryptoJS.enc.Utf8);
  return value
},

// 获取enckey
getenckey: function () {
  var strkey = 'AAAs0dj4BBjc8dwCCCC'
  var str = ''
  str += strkey.substring(3, 8)
  str += strkey.substring(10, 15)
  return str
},
// 生成秘钥enc
generateEnc(arr) {
  if (arr == null || arr.length == 0) {
    return "";
  }
  var contents = "";
  for (var i = 0; i < arr.length; i++) {
    contents += "[" + Object.keys(arr[i])[0] + "=" + arr[i][Object.keys(arr[i])[0]] + "]";
  }
  var datetime = new Date().Format('yyyy-MM-ddhh');
  contents += "[date=" + datetime + "]";
  contents += this.getenckey();
  console.log(contents)
  return md5.md5(contents).toLowerCase();
},
// 生成秘钥enc,自带enc参数排序功能
  generateEncSort(arr) {
          if (arr == null || arr.length == 0) {
            return "";
          }
          var contents = "";
          var objArr =[];
          var obj ={};
          for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < Object.keys(arr[i]).length; j++) {
              objArr.push((Object.keys(arr[i]))[j]);
              obj[(Object.keys(arr[i]))[j]] = arr[i][(Object.keys(arr[i]))[j]];
            }
          }
          console.log('排序前'+objArr)
          var len = objArr.length
          //按照ascii表对属性名首字母升序排序
          for(var i =0;i<len-1;i++){
            var count = 0;
            for(var j=0;j<len-i-1;j++){
              var f = objArr[j].substring(0, 1)
              var s = objArr[j+1].substring(0, 1)
              var n = 1
              while(f==s){
                f = objArr[j].substring(n, n+1)
                s = objArr[j+1].substring(n, n+1)
                n=n+1;
              } 
              if (f > s)//这是升序排法，前一个数和后一个数比较，如果前数大则与后一个数换位置
              {
                var temp = objArr[j];
                objArr[j] = objArr[j+1];
                objArr[j+1] = temp;
                count = 1;
              }
            }
            if (count == 0)     //如果某一趟没有交换位置，则说明已经排好序，直接退出循环
            break;
          }
          console.log('排序后'+objArr)
    
          for (var i = 0; i < len; i++) {
              contents += "[" + objArr[i] + "=" + obj[objArr[i]] + "]";
          }
    
          var datetime = new Date().Format('yyyy-MM-ddhh');
          contents += "[date=" + datetime + "]";
          contents += this.getenckey();
          console.log(contents)
          return md5.md5(contents).toLowerCase();
        }

})